import { reqUserLoginInfo } from "@/api/home";
import { reqUserInfo, reqUserLogoutInfo } from '@/api/user'

export default {
    namespaced: true,
    actions: {
        //用户登录
        async getUserLogin({ commit }, { username, password }) {
            let result = await reqUserLoginInfo(username, password)
            if (result.data.code == 200) {
                //存储token
                commit('GETTOKEN', { token: result.data.token, userID: result.data.profile.userId })
            }
            console.log(result.data);
            return result.data
        },
        //获取用户详情
        async getUser({ commit }, value) {
            let result = await reqUserInfo(value)
            if (result.data.code == 200) {
                commit('USERINFO', result.data)
            }
        },
        //退出登录
        async userLogout({ commit }) {
            let result = await reqUserLogoutInfo()
            if (result.data.code == 200) {
                commit('USERLOGOUTANDCLEARDATA')
            }
        }
    },

    mutations: {
        //修改是否登录
        CHNAGEISLOGIN(state, value) {
            state.isLogin = value
        },
        //保存token与用户id
        GETTOKEN(state, { token, userID }) {
            state.token = token
            state.userID = userID
            sessionStorage.setItem('token', token)
            sessionStorage.setItem('userID', userID)
        },
        //保存用户信息
        USERINFO(state, value) {
            state.userInfo = value || {}
        },
        //退出登录 清空数据
        USERLOGOUTANDCLEARDATA(state) {
            state.isLogin = false
            state.token = ''
            state.userID = ''
            state.userInfo = {}
            sessionStorage.removeItem('token')
            sessionStorage.removeItem('userID')
        },
    },

    state: {
        isLogin: false,
        token: sessionStorage.getItem('token') || '',
        userID: sessionStorage.getItem('userID') || '',
        userInfo: {},
    },

    getters: {
    },

}